import axios from 'axios'
import { Message } from 'element-ui'
import store from '../store/index'
import router from '../router/index'
axios.defaults.baseURL = 'http://localhost:8000'
// 请求超时时间
axios.defaults.timeout = 10000
// post请求头
axios.defaults.headers.get['Content-Type'] =
  'application/x-www-form-urlencoded;charset=UTF-8'
axios.defaults.headers.post['Content-Type'] = 'application/json;charset=UTF-8'
// axios.defaults.withCredentials = true
// axios.defaults.headers.common['token'] = token;
// 请求拦截器
axios.interceptors.request.use(
  (config) => {
    let token = localStorage.getItem('Authorization')
    if (token) {
      config.headers['ACCESS_TOKEN'] = token
      return config
      // config.headers['accessToken'] = Token;
    }
    return config
  },
  (error) => {
    Message({
      message: '请求失败' + response,
      type: 'error'
    })
    return Promise.error(error)
  }
)

// 响应拦截器
axios.interceptors.response.use(
  (response) => {
    if (response.status === 200) {
      if (response.data.code === 0) {
        Message({
          message: response.data.message,
          type: 'success'
        })
        return Promise.resolve(response)
      } else if (response.data.code === -99) {
        Message({
          message: response.data.message,
          type: 'error'
        })
        store.commit('deleteToken')
        store.commit('deleteUser')
        router.push('/login')
        return new Promise(() => {})
      } else {
        Message({
          message: response.data.message,
          type: 'error'
        })
        return new Promise(() => {})
      }
    } else {
      Message({
        message: '请求失败123' + response,
        type: 'error'
      })
      return new Promise(() => {})
    }
  },
  (error) => {
    Message({
      message: '服务器开小差了，请稍后再试',
      type: 'error'
    })
    return new Promise(() => {})
  }
)
